﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;


namespace CIT.WMS.input
{
    public partial class BRIOInput : Form
    {
        public BRIOInput()
        {
            InitializeComponent();
            CurrentTime = DateTime.Now;
            if (Utils.CheckConnectERP(out type))
            {
                flag_erpconnect = true;
            }

        }
        Utils.ERPType type;
        bool flag_erpconnect = false;
        private DateTime CurrentTime = new DateTime();
        private void btn_close_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void btn_yes_Click(object sender, EventArgs e)
        {
            Input();
        }

        private void txt_lotno_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                txt_datecode.SelectAll();
                txt_datecode.Focus();
            }
        }
        BarcodeUtils obj = new BarcodeUtils();

        void Input()
        {
            lab_msg.Text = "";
            if (txt_pocode.Text.Length == 0)
            {
                lab_msg.Text = "PO不可为空.";
                lab_msg.ForeColor = Color.Red;
                txt_pocode.SelectAll();
                txt_pocode.Focus();
                return;
            }
            BarcodeUtils.BarObject barobj = obj.AnalysisBarcode(Utils.AnalysisSerPath, txt_reelid.Text.Trim());

            //string pocode = "3302" + txt_pocode.Text;

            //if (pocode.Length != 15)
            //{
            //    lab_msg.Text = "采购订单不合法.";
            //    lab_msg.ForeColor = Color.Red;
            //    txt_reelid.SelectAll();
            //    txt_reelid.Focus();
            //    return;
            //}


            Utils.uContext.Accountk__BackingField = "mes40";

            if (!CheckPocode())
                return;



            //if (txt_reelid.Text.Length == 0)
            //{
            //    lab_msg.Text = "ReelID不可为空.";
            //    lab_msg.ForeColor = Color.Red;
            //    txt_reelid.SelectAll();
            //    txt_reelid.Focus();
            //    return;
            //}
            //DataTable dt = Utils.NMS.QueryDataTable(Utils.uContext, "select *from MdcDatMPN where newpn='" + txt_partnumber.Text + "'", new CIT.WMS.MESWcf.CmdParameter[0]);
            //if (dt.Rows.Count == 0)
            //{
            //    lab_msg.Text = "物料代码不合法.";
            //    lab_msg.ForeColor = Color.Red;
            //    txt_partnumber.SelectAll();
            //    txt_partnumber.Focus();
            //    return;
            //}
            DataTable dt_reelid = Utils.NMS.QueryDataTable(Utils.uContext, "select reelid from MdcDatVStorage where ReelID='" + barobj.reelId + "'", new CIT.WMS.MESWcf.CmdParameter[0]);
            if (dt_reelid != null && dt_reelid.Rows.Count > 0)
            {
                lab_msg.Text = "标签已存在.";
                lab_msg.ForeColor = Color.Red;
                txt_reelid.SelectAll();
                txt_reelid.Focus();
                return;
            }


            try
            {
                Convert.ToDecimal(txt_qty.Text);
            }
            catch
            {
                lab_msg.Text = "数量不合法.";
                lab_msg.ForeColor = Color.Red;
                txt_qty.SelectAll();
                txt_qty.Focus();
                return;
            }
            //
            string customerType = "";
            //if (txt_reelid.Text.Contains("}320+") || txt_reelid.Text.Contains("}023+"))
            //{
            //    customerType = "320";
            //}
            //else if (txt_reelid.Text.Contains("}002+"))
            //{
            //    customerType = "243";
            //}
            //else if (txt_reelid.Text.Contains("}002-"))
            //{
            //    customerType = "300";
            //}
            //else
            {
                customerType = txt_reelid.Text.Remove(0, 1).Split('+')[0];
            }
            Utils.uContext.Accountk__BackingField = "mes40";

            string mpn = "";
            string sql = string.Format(@"
select * from mdcdatMpn where (partcode1='{0}' or partcode2='{0}' or partcode3='{0}' or partcode4='{0}' or partcode5='{0}' or partcode6='{0}' or partcode7='{0}' or partcode8='{0}' or partcode9='{0}' or partcode10='{0}' or partcode11='{0}' or partcode12='{0}' or partcode13='{0}' or partcode14='{0}' ) and CustomerType='{1}'", txt_partnumber.Text, customerType);
            DataTable dt_pn = Utils.NMS.QueryDataTable(Utils.uContext, sql, new CIT.WMS.MESWcf.CmdParameter[0]);
            if (dt_pn.Rows.Count > 0)
            {
                txt_partnumber.Text = dt_pn.Rows[0]["newpn"].ToString();
                mpn = dt_pn.Rows[0]["partcode1"].ToString();
            }
            else
            {
                lab_msg.Text = "不存在MPN信息.";
                lab_msg.ForeColor = Color.Red;
                txt_qty.SelectAll();
                txt_qty.Focus();
                return;
            }
            #region 判断ERP中料号是否合法
            if (flag_erpconnect)
            {
                if (type == Utils.ERPType.YiFei)
                {
                    Utils.uContext.Accountk__BackingField = "erpinfo";
                    string sql_checkerp = "select * from  INVMB_V where MB001='" + txt_partnumber.Text + "'";
                    DataTable dt = Utils.NMS.QueryDataTable(Utils.uContext, sql_checkerp, new CIT.WMS.MESWcf.CmdParameter[0]);
                    if (dt.Rows.Count == 0)
                    {
                        lab_msg.Text = "当前料号在ERP中不存在";
                        lab_msg.ForeColor = Color.Red;
                        MessageBox.Show("当前料号在ERP中不存在");
                        return;
                    }
                    Utils.uContext.Accountk__BackingField = "mes40";
                }
            }

            #endregion
            //获取有效期
            if (dtpExpirationDate.Text.Trim().Length != 0)
            {
                try
                {
                    if (Regex.IsMatch(dtpExpirationDate.Text, "/"))
                    {
                        dtpExpirationDate.Text = DateTime.ParseExact(dtpExpirationDate.Text, "yyyy/MM/dd", System.Globalization.CultureInfo.CurrentCulture).ToString("yyyy/MM/dd");
                    }
                    else if (Regex.IsMatch(dtpExpirationDate.Text, "-"))
                    {
                        dtpExpirationDate.Text = DateTime.ParseExact(dtpExpirationDate.Text, "yyyy-MM-dd", System.Globalization.CultureInfo.CurrentCulture).ToString("yyyy/MM/dd");
                    }
                    else
                    {
                        dtpExpirationDate.Text = DateTime.ParseExact(dtpExpirationDate.Text, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture).ToString("yyyy/MM/dd");
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show("有效期时间格式不对");
                }
            }
            else
            {
                dtpExpirationDate.Text = DateTime.Now.AddYears(+1).ToString("yyyy/MM/dd").Trim();
            }
            StringBuilder str = new StringBuilder();
            //增加SyssystemLog日志  nancy 2017.07.26
            //新增 检查当前客供料采供订单中是否包含物料信息 frank 2017.09.06
            str.Append(string.Format(@"  if not exists(select * from mdcdatiqccheck where po='{1}' and pn='{2}') begin select '0','采供订单中不包含当前物料' end
                            declare @cnt int
                            --select  @cnt= count(findex) from MdcDatVStorage where datediff(dd,createtime,GETDATE())=0 findex存在null报错 nancy 2017.08.02 
                            select  @cnt= count(*) from MdcDatVStorage where datediff(dd,createtime,GETDATE())=0 
                            set @cnt=ISNULL(@cnt,0)+1
                            insert into mdcdatvstorage(CGUID,pocode,wocode,sfcno,HouseCode,ReelID,PartNumber,MPN,Qty,GRQty,SupplierID,DateCode,Batch1,Creator,Createtime,Updator,Updatetime,status,grtime,ExpirationDate,type,findex)
	                                        values(newid(),'{1}','','','007','{0}','{2}','{9}',{3},{3},'{4}','{7}','{5}','{6}',GETDATE(),'{6}',GETDATE(),'1',getdate(),'{8}','0',@cnt)
                                           insert SyssystemLog(Fguid,WoCode,SfcNo,ProuctCode,PartNumber,ReelID,pocode,SupplierID,HouseCode,Qty,Remarks,Creator)
                                           values(newid(),'','','','{2}','{0}','{1}','{4}','007',{3},'PDA客户料绑定','{6}') select '1','绑定成功'
                                         ", barobj.reelId, txt_pocode.Text, txt_partnumber.Text, txt_qty.Text, txt_vendor.Text, txt_lotno.Text, Utils.uContext.UserNamek__BackingField, txt_datecode.Text, dtpExpirationDate.Text, mpn));

            DataTable dt_result = Utils.NMS.QueryDataTable(Utils.uContext, str.ToString(), new CIT.WMS.MESWcf.CmdParameter[0]);
            if (dt_result.Rows[0][0].ToString() == "0")
            {
                lab_msg.Text = dt_result.Rows[0][1].ToString(); lab_msg.ForeColor = Color.Red;
                txt_reelid.SelectAll();
                txt_reelid.Focus();
                return;
            }
            else
            {
                Utils.SaveAppropriationSheet(new AppropriationSheet() { MType = "5", PartNumber = txt_partnumber.Text, WOCode = "", POCode = txt_pocode.Text, ReelID = barobj.reelId, Qty = txt_qty.Text, Description = "客供绑定", HouseCode = "007", FromHouse = "", User = Utils.uContext.UserNamek__BackingField });

                lab_msg.Text = "绑定成功.";
                lab_msg.ForeColor = Color.Lime;
                txt_lotno.Text = "";
                txt_partnumber.Text = "";
                txt_qty.Text = "";
                txt_reelid.Text = "";
                txt_vendor.Text = "";
                txt_reelid.SelectAll();
                txt_reelid.Focus();
                return;
            }

        }

        private void txt_pocode_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                CheckPocode();
            }
        }

        private void txt_reelid_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                BarcodeUtils.BarObject barobj = obj.AnalysisBarcode(Utils.AnalysisSerPath, txt_reelid.Text);
                CurrentTime = DateTime.Now;
                DataTable dt_reelid = Utils.NMS.QueryDataTable(Utils.uContext, "select reelid from MdcDatVStorage where ReelID='" + barobj.reelId + "'", new CIT.WMS.MESWcf.CmdParameter[0]);
                if (dt_reelid.Rows.Count > 0)
                {
                    lab_msg.Text = "标签已存在.";
                    lab_msg.ForeColor = Color.Red;
                    txt_reelid.SelectAll();
                    txt_reelid.Focus();
                    return;
                }
                txt_partnumber.SelectAll();
                txt_partnumber.Focus();
            }
        }
        bool CheckPocode()
        {
            Utils.uContext.Accountk__BackingField = "mes40";

            //判断采购订单是否合法
            DataTable dt = Utils.NMS.QueryDataTable(Utils.uContext, "[sp_CheckKPO] '" + txt_pocode.Text + "'", new CIT.WMS.MESWcf.CmdParameter[0]);
            if (dt.Rows[0][0].ToString() == "0")
            {
                lab_msg.Text = dt.Rows[0][1].ToString();
                lab_msg.ForeColor = Color.Red;
                txt_pocode.SelectAll();
                txt_pocode.Focus();
                return false;
            }
            txt_reelid.SelectAll();
            txt_reelid.Focus();
            return true;
        }

        private void txt_partnumber_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                //Utils.uContext.Accountk__BackingField = "mes40";
                //DataTable dt = Utils.NMS.QueryDataTable(Utils.uContext, "select *from MdcDatMPN where newpn='" + txt_partnumber.Text + "'", new CIT.WMS.MESWcf.CmdParameter[0]);
                //if (dt.Rows.Count == 0)
                //{
                //    lab_msg.Text = "物料代码不合法.";
                //    lab_msg.ForeColor = Color.Red;
                //    txt_partnumber.SelectAll();
                //    txt_partnumber.Focus();
                //    return;
                //}
                txt_qty.SelectAll();
                txt_qty.Focus();
            }
        }

        private void txt_qty_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                txt_lotno.SelectAll();
                txt_lotno.Focus();
            }
        }

        private void txt_datecode_KeyPress(object sender, KeyPressEventArgs e)
        {
            #region 扫描失败屏蔽 nancy 2017.07.27
            //if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)13 && e.KeyChar != (char)8)
            //{
            //    e.Handled = true;
            //}
            #endregion
            if (e.KeyChar == 13)
            {
                dtpExpirationDate.SelectAll();
                dtpExpirationDate.Focus();
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (DateTime.Now.AddMinutes(-10) > CurrentTime)
            {
                this.Close();
            }
        }

        private void txt_vendor_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                if (txt_vendor.Text.Length == 0)
                {
                    lab_msg.Text = "生产厂商不可为空.";
                    lab_msg.ForeColor = Color.Red;
                    txt_vendor.Focus();
                    return;
                }
                Input();
            }
        }

        private void dtpExpirationDate_KeyPress(object sender, KeyPressEventArgs e)
        {
            #region 扫描失败屏蔽 nancy 2017.07.27
            //if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)13 && e.KeyChar != (char)8)
            //{
            //    e.Handled = true;
            //}
            #endregion
            if (e.KeyChar == 13)
            {
                txt_vendor.SelectAll();
                txt_vendor.Focus();
            }
        }
    }
}